package com.zhuang.controller;

import com.zhuang.dto.CommentDTO;
import com.zhuang.dto.QuestionDTO;
import com.zhuang.pojo.Notification;
import com.zhuang.pojo.User;
import com.zhuang.service.CommentService;
import com.zhuang.service.NotificationService;
import com.zhuang.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class QuestionController {

    @Autowired
    QuestionService questionService;

    @Autowired
    CommentService commentService;

    @Autowired
    NotificationService notificationService;


    @GetMapping("/question/{id}")
    public String question(@PathVariable(name = "id") Integer id,
                           Model model,
                           HttpSession session) {

        QuestionDTO questionDTO = questionService.getQuestion(id);
        List<CommentDTO> commentDTOList = commentService.getByParentId(id, 1);
        for (CommentDTO commentDTO : commentDTOList) {
            List<CommentDTO> byParentId = commentService.getByParentId(commentDTO.getId().intValue(), 2);
            int size = byParentId.size();
            commentDTO.setChildCommentCount(size);
        }
        List<QuestionDTO> relatedQuestion = questionService.selectRelated(questionDTO);
        questionService.addViewCount(id);
        // 计算消息未读数
        User user = (User) session.getAttribute("user");
        Integer count = notificationService.count(user.getAccountId().longValue());
        model.addAttribute("count", count);

        model.addAttribute("question", questionDTO);
        model.addAttribute("comments", commentDTOList);
        model.addAttribute("relatedQuestion", relatedQuestion);
        return "question";
    }
}
